package com.example.websocketpoint2point.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.security.Principal;

/**
 * @author ljw
 * @description
 * @date 2022/4/8 7:45
 */
@Controller
public class WsController {

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    /**
     * 监控 前端消息
     * @param principal 当前用户信息
     * @param msg 消息
     * @author ljw
     * @date 2022/4/8 7:49 
     */
    @MessageMapping("/chat")
    public void handleChat(Principal principal, String msg) {
        //硬编码判断发送人，并给另外一个人发送消息
        if (principal.getName().endsWith("wyf")) {
            //第一个参数是接收消息的用户，第二个是浏览器订阅的地址，第三个是消息本身
            simpMessagingTemplate.convertAndSendToUser("wisely", "/queue/notifications", principal.getName()+"-send:"+msg);
        } else {
            simpMessagingTemplate.convertAndSendToUser("wyf", "/queue/notifications", principal.getName()+"-send:"+msg);
        }
    }
}
